<template>
  <div class="warehouse-pickup-container">
    <!-- 顶部搜索栏 -->
    <div class="search-bar">
      <el-input
          v-model="searchQuery"
          placeholder="搜索商品名称或编码"
          clearable
          class="search-input"
          @input="handleSearch"
      >
        <template #prefix>
          <el-icon>
            <Search/>
          </el-icon>
        </template>
      </el-input>
      <el-button type="primary" style="margin-left: 100px"
                 @click="openNewTab('http://localhost:8080/finishProduct/getAllFinishProductVo')">查看bom图
      </el-button>
      <el-button type="warning" style="margin-left: 80px"
                 @click="router.push('/user/orderDetail')">查看订单
      </el-button>


      <el-text style="margin-left: 500px">你好呀,{{ nickname }}</el-text>

      <el-button type="danger" style="margin-left: 100px" @click="logout">退出登录</el-button>

    </div>

    <div class="main-content">
      <!-- 左侧分类筛选 -->
      <div class="category-sidebar">
        <h3 class="sidebar-title">商品分类</h3>
        <el-scrollbar>
          <el-menu
              :default-active="activeCategory"
              @select="handleCategorySelect"
          >
            <el-menu-item
                v-for="category in categories"
                :key="category.id"
                :index="category.id"
            >
              {{ category.name }} ({{ category.productCount }})
            </el-menu-item>
          </el-menu>
        </el-scrollbar>
      </div>

      <!-- 商品展示区 -->
      <div class="goods-list">
        <div class="goods-grid">
          <div
              v-for="product in paginatedProducts"
              :key="product.id"
              class="goods-card"
          >
            <div class="goods-image">
              <img :src="product.productImage" alt="商品图片">
              <div class="stock-badge">库存: {{ product.stock }}</div>
            </div>
            <div class="goods-info">
              <h4 class="goods-title">{{ product.name }}</h4>
              <p class="goods-sku">编码: {{ product.sku }}</p>
              <div class="goods-footer">

                <el-button
                    type="primary"
                    size="small"
                    :disabled="product.stock <= 0"
                    @click="addToCart(product)"
                >
                  <el-icon>
                    <ShoppingCart/>
                  </el-icon>
                  加入提货单
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="filteredProducts.length"
              :page-sizes="[12, 24, 48]"
              layout="total, sizes, prev, pager, next, jumper"
              background
          />
        </div>
      </div>

      <!-- 右侧购物车 -->
      <div class="cart-sidebar">
        <div class="cart-header">
          <h3>提货清单</h3>
          <el-tag type="info">共 {{ cartTotalItems }} 件</el-tag>
        </div>

        <el-scrollbar class="cart-items">
          <div
              v-for="item in cartItems"
              :key="item.id"
              class="cart-item"
          >
            <div class="item-info">
              <div class="item-name">{{ item.name }}</div>
              <div class="item-sku">编码: {{ item.sku }}</div>
            </div>
            <div class="item-controls">
              <el-input-number
                  v-model="item.quantity"
                  :min="1"
                  :max="item.stock"
                  size="small"
                  @change="updateCartItem(item)"
              />
              <el-button
                  type="danger"
                  size="small"
                  @click="removeFromCart(item.id)"
              >
                删除
              </el-button>
            </div>
          </div>
        </el-scrollbar>

        <div class="cart-footer">

          <el-button
              type="success"
              size="large"
              class="submit-btn"
              :disabled="cartTotalItems === 0"
              @click="submitOrder"
          >
            提交提货申请
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted} from 'vue'
import {Plus, Search, ShoppingCart} from '@element-plus/icons-vue'
import {addOrders, getAllCategoriesInfo, getAllProducts, getUserNickName} from "@/api/auth.js";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";

const nickname = ref()
// 模拟数据
const categories = ref([
  {id: 'all', name: '全部商品', productCount: 45},
  {id: '1', name: '电子元件', productCount: 12},
  {id: '2', name: '机械零件', productCount: 8},
  {id: '3', name: '化工原料', productCount: 15},
  {id: '4', name: '包装材料', productCount: 10}
])
const initData = async () => {
  try {
    const res = await getAllCategoriesInfo()
    if (res.code === 200) {
      categories.value = res.data
    }
  } catch (e) {
    ElMessage.error(e)
  }
  try {
    const res = await getAllProducts()
    if (res.code === 200) {
      products.value = res.data
    }
  } catch (e) {
    ElMessage.error(e)
  }
  try {
    const res=await getUserNickName()
    if(res.code===200){
      nickname.value=res.data
    }
  }catch (e){
    ElMessage.error(e)
  }

}
onMounted(() => {
  initData()
})
const openNewTab = (url) => {
  window.open(url, '_blank', 'noopener,noreferrer')
}
const products = ref([
  {
    id: 1,
    sku: 'IPHONE15_128G',
    name: 'iPhone 15 128GB',
    brandName: {id: 1, name: '苹果'},
    categoryName: {id: 4, name: '手机'},
    productImage: 'https://pic3.zhimg.com/v2-18a6d0127cec1faa5122b6bc283bb9ab_r.jpg?source=1940ef5c',
    stock: 1244,
    createdAT: '2025-04-23T20:15:46',
    createdName: '周兴'
  }])

// 状态管理
const searchQuery = ref('')
const activeCategory = ref(null)
const currentPage = ref(1)
const pageSize = ref(12)
const cartItems = reactive([])
const logout=()=>{
  localStorage.removeItem('token')
  initData()

}
// 计算属性
const filteredProducts = computed(() => {
  return products.value.filter(p => {
    const searchTerm = searchQuery.value.toLowerCase()
    const matchSearch = p.name.toLowerCase().includes(searchTerm) ||
        p.sku.toLowerCase().includes(searchTerm) ||
        p.brandName.name.toLowerCase().includes(searchTerm)

    const matchCategory = !activeCategory.value ||
        p.categoryName.id === activeCategory.value

    return matchSearch && matchCategory
  })
})

const paginatedProducts = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredProducts.value.slice(start, start + pageSize.value)
})

// 购物车相关
const cartTotalItems = computed(() =>
    cartItems.reduce((sum, item) => sum + item.quantity, 0)
)

const cartTotalAmount = computed(() =>
    cartItems.reduce((sum, item) => sum + (item.price * item.quantity), 0)
)

// 操作方法
const addToCart = (product) => {
  const existing = cartItems.find(item => item.id === product.id)
  if (existing) {
    existing.quantity++
  } else {
    cartItems.push({
      ...product,
      quantity: 1
    })
  }
}

const updateCartItem = (item) => {
  if (item.quantity > item.stock) {
    item.quantity = item.stock
    ElMessage.warning('超过库存数量')
  }
}

const removeFromCart = (id) => {
  const index = cartItems.findIndex(item => item.id === id)
  if (index !== -1) cartItems.splice(index, 1)
}

const submitOrder = async () => {

  try {
    const payload = {
      items: cartItems.map(item => ({
        productId: item.id,
        quantity: item.quantity
      }))

    }

    try {
      const res = await addOrders(payload)
      if (res.code === 200) {
        ElMessage.success('提货申请已提交')
      } else {
        ElMessage.error(res.message)
      }
    } catch (e) {
      ElMessage.error(e.message)
    }
    await initData()
    cartItems.splice(0, cartItems.length)
  } catch (error) {
    ElMessage.error('提交失败，请重试')
  }
}

// 界面交互
const handleCategorySelect = (categoryId) => {
  activeCategory.value = activeCategory.value === categoryId ? null : categoryId
  currentPage.value = 1
}

const handleSearch = () => {
  currentPage.value = 1
}
</script>

<style scoped>
.warehouse-pickup-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.search-bar {
  padding: 20px;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.search-input {
  width: 400px;
}

.main-content {
  flex: 1;
  display: flex;
  padding: 20px;
  gap: 20px;
}

.category-sidebar {
  width: 240px;
  background: #fff;
  border-radius: 8px;
  padding: 15px;
}

.sidebar-title {
  margin: 0 0 15px 0;
  color: #333;
}

.goods-list {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
}

.goods-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
}

.goods-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
  transition: transform 0.3s ease;
}

.goods-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.goods-image {
  position: relative;
  height: 180px;
  background: #f8fafc;
}

.goods-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.stock-badge {
  position: absolute;
  bottom: 10px;
  left: 10px;
  background: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.goods-info {
  padding: 15px;
}

.goods-title {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #333;
}

.goods-sku {
  margin: 0 0 12px 0;
  color: #999;
  font-size: 12px;
}

.goods-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.goods-price {
  color: #f56c6c;
  font-weight: bold;
}

.cart-sidebar {
  width: 320px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.cart-items {
  flex: 1;
  margin: 15px 0;
}

.cart-item {
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.item-info {
  margin-bottom: 8px;
}

.item-name {
  font-size: 13px;
  color: #333;
}

.item-sku {
  font-size: 12px;
  color: #999;
}

.item-controls {
  display: flex;
  gap: 8px;
  align-items: center;
}

.cart-footer {
  border-top: 1px solid #eee;
  padding-top: 15px;
}

.total-amount {
  text-align: right;
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
  margin-bottom: 15px;
}

.submit-btn {
  width: 100%;
}

.pagination {
  margin-top: 20px;
  padding: 15px 0;
  border-top: 1px solid #eee;
}
</style>